/* Copyright (c) 2010, Peter Lényi */
/* Licensed under The BSD License. */

package gem.apps.fs.web;

import gem.apps.fs.engine.FileServer;
import gem.apps.fs.entities.FileMeta;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet class FileDeletePostServlet authorizes the deletion and then calls
 * application login to delete the chosen file. The turns control over to the jsp
 * listing files.
 *
 * @author Peter Lényi
 * @version 20100425F
 */
public class FileDeletePostServlet extends HttpServlet
{
    private static final String ADDRESS_FATAL = "/error/fatal/jsp";
    private static final String ADDRESS_WARNING = "/file/delete/jsp";
    private static final String ADDRESS_SUCCESS = "/file/list/pre";
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // prepare local variables
        boolean success = false;
        List<String> messages = new ArrayList<String>();
        
        // prepare resources
        FileServer fs = FileServer.getInstance();
        ResourceBundle gui = ResourceBundle.getBundle("Gui");

        // load request parameters
        String uinString = request.getParameter("form.uin");
        String password = request.getParameter("form.password");
        if (password == null) {
            password = "";
        }

        // execute logic
        try {
            long uin = Long.parseLong(uinString);
            FileMeta filemeta = fs.getFileMeta(uin);
            if (filemeta.getPassword().equals(password)) {
                if (fs.deleteFile(uin)) {
                    messages.add(gui.getString("Gui.action.file.delete.done"));
                    success = true;
                }
                else {
                    messages.add(gui.getString("Gui.action.file.delete.err"));
                }
            }
            else {
                messages.add(gui.getString("Gui.action.authorize.no"));
            }
            request.getSession().setAttribute("msg", messages);
            
            // pass connection
            if (success) {
                response.sendRedirect(getServletContext().getContextPath() + ADDRESS_SUCCESS);
            }
            else {
                response.sendRedirect(getServletContext().getContextPath() + ADDRESS_WARNING + "?uin=" + uin);
            }
        }
        catch (NumberFormatException ex) {
            response.sendRedirect(getServletContext().getContextPath() + ADDRESS_FATAL);
        }
    }
}
